﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using esri.ParaSeting;
using esri.DataBase;
using esri.Detect;
using esri3;

namespace esri1
{
    ////////////////////
    /////场检查
    namespace FieldInitial
    {
        class FieldInit
        {
            public long GridCount;
            private static FieldInit finit;
            public static FieldInit CtInstance()
            {
                if(finit==null)
                    finit=new FieldInit();
                return finit;
            }
            public struct RES_GRID
            {
                public string GID;
                public double Center_X;
                public double Center_Y;
                public double First_H;
                public double Last_H;
                
            }
            public RES_GRID[] m_GridArr_current,m_GridArr_former;//用来存储已存在结果表的格子，当前层和前一层
            //public RES_GRID[] GridArr
            //{
            //    get { return GridArr; }
            //    set { GridArr = value; }
            //}
            public FieldInit()
            { }
            public void setGridCount(int count)//重载构造函数,根据结果表初始化格子数组
            {
                GridCount = count;
                m_GridArr_current = new RES_GRID[count];
                m_GridArr_former = new RES_GRID[count];
            }

            //public void CurrentGrid_Init(string ID, double X, double Y, int index)
            //{
             //   m_GridArr_current[index].GID = ID;
            //    m_GridArr_current[index].Center_X = X;
            //    m_GridArr_current[index].Center_Y = Y;
            //}
            public void CurrentGrid_Init(string ID, double X, double Y, double H1, double H2, int index)//为当前层的数组赋值
            {
                m_GridArr_current[index].GID = ID;
                m_GridArr_current[index].Center_X = X;
                m_GridArr_current[index].Center_Y = Y;
                m_GridArr_current[index].First_H = H1;
                m_GridArr_current[index].Last_H = H2;
            }
            public void FormerGrid_Init(string ID, double X, double Y, double H1, double H2, int index)//为前一层的数组赋值
            {
                m_GridArr_former[index].GID = ID;
                m_GridArr_former[index].Center_X = X;
                m_GridArr_former[index].Center_Y = Y;
                m_GridArr_former[index].First_H = H1;
                m_GridArr_former[index].Last_H = H2;
            }

        }
    }
    namespace Fieldevaluation
    {
        
        class ElevationCal//高程计算
        {
            public ElevationCal()
            { }
            /// <summary>
            /// 读表,算高程,写表时所用的若干结构体定义
            /// </summary>
            struct tp
            {
                public double x;
                public double y;
                public double h;
                public bool ischecked;
            }//点信息结构体
            tp tempPoint=new tp();
            ArrayList PointArray = new ArrayList();
            tp[] PointInfo;
            struct tempgi
            {
                public string GID;
                public double Center_X;
                public double Center_Y;
                public double First_H;
                public double Last_H;
                public ArrayList H;
                public long p_count;
            }//格子信息结构体
            tempgi tempGridInfo=new tempgi();
            
            ArrayList GridInfoArray = new ArrayList();
            tempgi[] GridInfo;
            struct ga
            {
                public string GID;
                public double Center_X;
                public double Center_Y;
            }
            ga[] GridArray;

            //double[,] H = new double[400000,1000];
            int number_grid = 0, number_point = 0, grid_count = 0;//总格子数,总点数,和范围内的格子数
            ///定义结束
            ///
            public void Elevation_Calculate(string fieldno)
            {
                
                Elevation_Initial(fieldno);//初始化计算所用的变量
                Elevation_Decide();//根据不同情况计算高程
                Elevation_UpdateDB(fieldno);//计算结果入库
                
            }
            public int Elevation_Initial(string field)
            {
                /////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////////////////////
                ////////////////////////////读取符合条件的点
                DBConnection DBC = DBConnection.Instance();
                DBOperation DBO = new DBOperation();
                SqlDataReader dr_name, dr_query;
                DBO.ConnectionString = DBC.ConnectionString;
                SqlConnection conn = DBO.Connect();
                string str_name, str_query, str_countquery;
                str_name = "SELECT name FROM sys.sysobjects WHERE (xtype = 'U') AND (name LIKE '%TBLGPSDATA_1000_133_" + field.ToString() + "%')";
                //MessageBox.Show(str_name.ToString());
                SqlCommand sqlcmd_name = new SqlCommand();
                SqlCommand sqlcmd_query = new SqlCommand();
                sqlcmd_name.CommandText = str_name;
                sqlcmd_name.Connection = conn;
                //conn.Open();
                dr_name = sqlcmd_name.ExecuteReader();
                //DBO.CloseConnection();

                
                
                while (dr_name.Read())
                {

                    str_query = "SELECT * FROM  dbo." + dr_name[0].ToString() + " WHERE (STATUE = 4)";
                    DBOperation dbo = new DBOperation();
                    dbo.ConnectionString = DBC.ConnectionString;
                    SqlConnection conn1 = dbo.Connect();
                    sqlcmd_query.CommandText = str_query;
                    sqlcmd_query.Connection = conn1;
                    //dbo.CloseConnection();
                    dr_query = sqlcmd_query.ExecuteReader();
                    while (dr_query.Read())
                    {
                        tempPoint.x = Convert.ToDouble(dr_query.GetValue(8));
                        tempPoint.y = Convert.ToDouble(dr_query.GetValue(7));
                        tempPoint.h = Convert.ToDouble(dr_query.GetValue(9));
                        tempPoint.ischecked = false;
                        PointArray.Add(tempPoint);
                        number_point++;
                    }
                    dr_query.Close();
                    //dbo.CloseConnection();
                }
                dr_name.Close();
                PointInfo=new tp[PointArray.Count];
                PointArray.CopyTo(PointInfo);
                PointArray.Clear();
                //DBO.CloseConnection();
                ////////////////////////////////////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //////////////以上为点的读取过程
                //////读取格子的过程
                string str_grid = "select * from dbo.TABLE_NY_RESULT";
                string str_count = "select count(*) from dbo.TABLE_NY_RESULT";
                SqlCommand sqlcmd_grid = new SqlCommand(str_grid, conn);
                SqlDataReader dr_grid = sqlcmd_grid.ExecuteReader();

                DBOperation dbocount = new DBOperation();
                dbocount.ConnectionString = DBC.ConnectionString;
                SqlConnection conncount = dbocount.Connect();
                SqlCommand sqlcmd_grid_count = new SqlCommand(str_count, conncount);
                number_grid = Convert.ToInt32(sqlcmd_grid_count.ExecuteScalar());
                int index=0;
                GridArray=new ga[number_grid];
                
                
                
                ProgressBar pBar = new ProgressBar();
                ProgressBar pBarPoint = new ProgressBar();
                pBar.progressBar1.Maximum = number_grid;
                pBar.Text = "Reading Grids";
                pBar.Show();




                while (dr_grid.Read())
                {
                    GridArray[index].GID = dr_grid.GetValue(0).ToString();
                    GridArray[index].Center_X = Convert.ToDouble(dr_grid.GetValue(1));
                    GridArray[index].Center_Y = Convert.ToDouble(dr_grid.GetValue(2));
                    index++;
                    pBar.progressBar1.Value = index;
                }
                pBar.Hide();
                dr_grid.Close();
                DBO.CloseConnection();
                //////////////读取格子信息完毕
                
                ///////////////////////判断点与格子关系,得到范围内的格子
                tempGridInfo.H = new ArrayList();
                int i, h_index;
                
                pBar.progressBar1.Maximum = number_grid;
                pBar.Text="point and grids";
                pBar.Show();
                for (i = 0; i < number_grid; i++)
                {
                    pBarPoint.progressBar1.Maximum = PointInfo.Length;
                    pBarPoint.Text = "juding gird " + i.ToString();
                    pBarPoint.Left = pBar.Left + 300;
                    pBarPoint.Top = pBar.Top + 300;
                    pBarPoint.Show();
                    h_index = 0;
                    bool flag = false;
                    for(int j=0;j<PointInfo.Length;j++)
                    {
                        if ((!PointInfo[j].ischecked) && (Math.Sqrt(Math.Pow((PointInfo[j].x - GridArray[i].Center_X), 2) + Math.Pow((PointInfo[j].y - GridArray[i].Center_Y), 2)) <= 0.2))
                        {
                            tempGridInfo.GID = GridArray[i].GID;
                            tempGridInfo.Center_X = GridArray[i].Center_X;
                            tempGridInfo.Center_Y = GridArray[i].Center_Y;
                            tempGridInfo.H.Add(PointInfo[j].h);
                            PointInfo[j].ischecked = true;
                            h_index++;
                            flag = true;
                        }
                        pBarPoint.progressBar1.Value = j;
                        
                    }
                    
                    if (flag)
                    {
                        grid_count++;
                        tempGridInfo.p_count = h_index;
                        GridInfoArray.Add(tempGridInfo);
                        tempGridInfo.H.Clear();
                    }
                    pBarPoint.Hide();
                    pBar.progressBar1.Value = i;
                }
                pBar.Hide();
                GridInfo=new tempgi[GridInfoArray.Count];
                GridInfoArray.CopyTo(GridInfo);
                GridInfoArray.Clear();
                return GridInfo.Length;
                
            }
            public void Elevation_Decide()
            {
                double max, min;
                int i, j;
                
                for(i=0;i<GridInfo.Length;i++)
                {
                    
                    if (GridInfo[i].H.Count >= 2)
                    {
                        GridInfo[i].H.Sort(0, GridInfo[i].H.Count, null);
                        GridInfo[i].Last_H = Convert.ToDouble(GridInfo[i].H[0]);
                        GridInfo[i].First_H = Convert.ToDouble(GridInfo[i].H[GridInfo[i].H.Count]);
                    }
                }
                
            }
            public void Elevation_UpdateDB(string tablename)
            {
                DBConnection DBC = DBConnection.Instance();
                DBOperation DBO = new DBOperation();
                DBO.ConnectionString = DBC.ConnectionString;
                SqlConnection conn = DBO.Connect();
                string str_create, str_open;
                str_create = "create table dbo.GPSTBL_H_" + tablename.Insert(4, "_")+" "+"(GID char(20),Center_X real,Center_Y real,First_H real,Last_H real)";
                SqlCommand cmd_create = new SqlCommand(str_create, conn);
                cmd_create.ExecuteNonQuery();
                cmd_create.Dispose();

                str_open = "select * from dbo.GPSTBL_H_" + tablename.Insert(4, "_");
                SqlDataAdapter da = new SqlDataAdapter(str_open, conn);
                SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
                da.InsertCommand = cmdBuilder.GetInsertCommand();

                DataSet ds = new DataSet();
                da.FillSchema(ds, SchemaType.Mapped);
                DataTable dt = ds.Tables[0];
                
                /////////////////////////////////////////////////////////////
                
                for (int i = 0; i < 90; i++)
                {
                    DataRow row = dt.NewRow();
                    row["GID"] = GridInfo[i].GID;
                    row["Center_X"] = GridInfo[i].Center_X;
                    row["Center_Y"] = GridInfo[i].Center_Y;
                    row["First_H"] = GridInfo[i].First_H;
                    row["Last_H"] = GridInfo[i].Last_H;
                    dt.Rows.Add(row);

                }
                da.Update(ds);
                conn.Close();
            }
        }
    }
}
